<script setup>
import { ref, onBeforeMount, onBeforeUnmount } from "vue";
import {
  getQrCodeKey,
  getQrCode,
  checkScanStatus,
} from "@/apis/login";
import { useCookieStore } from "@/stores";

const emits = defineEmits(['loginSuc'])

const cookieStore = useCookieStore();

const qrCode = ref("");
const scanMessage = ref("网易云音乐扫码登录");
const checkTimer = ref(null);
const isLoading = ref(true);
const isShowBtn = ref(false);
const createQrCode = async () => {
  const keyData = await getQrCodeKey();
  const codeData = await getQrCode({
    key: keyData.data.unikey,
    qrimg: true,
  });
  if (codeData.code !== 200) {
    isShowBtn.value = true;
    return uni.showToast({
      title: "二维码获取失败，请重试",
      icon: "none",
    });
  }
  qrCode.value = codeData.data.qrimg;
  isLoading.value = false;
  isShowBtn.value = false;
  checkTimer.value = setInterval(async () => {
    const checkData = await checkScanStatus({ key: keyData.data.unikey });
    const code = checkData.code;
    scanMessage.value = checkData.message;
    if (code === 803) {
      clearInterval(checkTimer.value);
      cookieStore.cookie = checkData;
      emits('loginSuc')
    } else if (code === 800) {
      isShowBtn.value = true;
      clearInterval(checkTimer.value);
    }
  }, 2000);
};

onBeforeMount(() => {
  createQrCode();
});

onBeforeUnmount(() => {
  clearInterval(checkTimer.value);
});
</script>

<template>
  <view class="qrCode-wrap">
    <view class="qrCode-img-wrap">
      <image class="qrCode-img" :src="qrCode" mode="aspectFit" />
      <view class="qrCode-status">
        <uni-load-more status="loading" v-show="isLoading" />
        <button
          class="scan-tip"
          type="primary"
          v-show="isShowBtn"
          @tap="createQrCode"
        >
          重新获取
        </button>
      </view>
    </view>
    <view class="scan-tip"> {{ scanMessage }}</view>
  </view>
</template>

<style lang="scss">
.qrCode-wrap {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  .qrCode-img-wrap {
    margin: 40rpx 0;
    position: relative;
    height: 450rpx;
    width: 450rpx;
    .qrCode-img {
      height: 100%;
      width: 100%;
    }
    .qrCode-status {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      margin: 20rpx auto;
      height: 400rpx;
      width: 400rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .scan-tip {
    font-size: 28rpx;
    font-weight: bold;
    letter-spacing: 2rpx;
  }
}
</style>
